package dmitrygusev.ratings.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import dmitrygusev.io.StringUtils;
import dmitrygusev.ratings.services.Matcher;

public class MoviePack {

	private List<Movie> movies = new ArrayList<Movie>();
	
	public MoviePack(Movie movie) {
		addMovie(movie);
	}
	
	public List<Movie> getMovies() {
		return Collections.unmodifiableList(movies);
	}
	
	public void addMovie(Movie movie) {
		movies.add(movie);
	}

	public boolean isTitle2Available() {
		return ! StringUtils.isNullOrEmpty(getTitle2());
	}

	private String title2 = "";
	
	public String getTitle2() {
		if (! StringUtils.isNullOrEmpty(title2)) {
			return title2;
		}
		
		for (Movie movie : movies) {
			if (! StringUtils.isNullOrEmpty(movie.getTitle())) {
				if (! Matcher.titlesAreTheSame(movie.getTitle(), getTitle())) {
					//	title2 may contain HTML entities which looks better in HTML
					if (movie.getTitle().length() > title2.length()) {
						title2 = movie.getTitle();
					}
				}
			}
			if (! StringUtils.isNullOrEmpty(movie.getTitle2())) {
				if (! Matcher.titlesAreTheSame(movie.getTitle2(), getTitle())) {
					if (movie.getTitle2().length() > title2.length()) {
						title2 = movie.getTitle2();
					}
				}
			}
		}
		return title2;
	}

	private String coverPicture;
	
	public String getCoverPicture() {
		if (! StringUtils.isNullOrEmpty(coverPicture)) {
			return coverPicture;
		}
		
		for (Movie movie : movies) {
			if (! StringUtils.isNullOrEmpty(movie.getCoverPicture())) {
				coverPicture = movie.getCoverPicture();
				break;
			}
		}
		
		return coverPicture;
	}

	public String getYear() {
		return getDefaultMovie().getYear();
	}

	public String getTitle() {
		return getDefaultMovie().getTitle();
	}

	private Movie getDefaultMovie() {
		return movies.get(0);
	}
}
